package org.opens.javaskill.design;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 功能:
 *      解释器模式的demo.
 */
public class InterpreterPattern {

    public static void main(String[] args) {
        Context context = new Context();
        context.freeRide("韶关的老人");
        context.freeRide("韶关的青年");
        context.freeRide("西安的老人");
    }

}

interface MyExpression {

    public boolean interpret(String info);

}

class TerminalMyExpression implements MyExpression {

    private Set<String> validSet = new HashSet<>();

    public TerminalMyExpression(String[] validArr) {
        this.validSet.addAll(Arrays.asList(validArr));
    }

    @Override
    public boolean interpret(String info) {
        return validSet.contains(info);
    }

}

class AndMyExpression implements MyExpression {

    private MyExpression expression1 = null;

    private MyExpression expression2 = null;

    public AndMyExpression(MyExpression expression1, MyExpression expression2) {
        this.expression1 = expression1;
        this.expression2 = expression2;
    }

    @Override
    public boolean interpret(String info) {
        String[] resTemp = info.split("的");
        return expression1.interpret(resTemp[0]) && expression2.interpret(resTemp[1]);
    }

}

class Context {

    private String[] citys = new String[]{"韶关", "广州"};

    private String[] persons = {"老人", "妇女", "儿童"};

    private MyExpression expression;

    public Context() {
        TerminalMyExpression expression1 = new TerminalMyExpression(citys);
        TerminalMyExpression expression2 = new TerminalMyExpression(persons);

        this.expression = new AndMyExpression(expression1, expression2);
    }

    public void freeRide(String info) {
        boolean validRes = this.expression.interpret(info);
        if ( validRes ) {
            System.out.println("你是" + info + ", 本次乘车免费");
            return;
        }
        System.out.println("你是" + info + ", 本次乘车投币2元");
    }

}